<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
function curl_get_file_contents($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

	$file_contents = curl_exec($ch);
	curl_close($ch);

	return $file_contents;
}

function curl_post($url, $content) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
	curl_exec($ch);
	curl_close($ch);
}

function checkNull($subject) {
	$isNull = is_null($subject);

	if (is_string($subject)) {
		$isNull = empty($subject);
	}

	if (is_array($subject)) {
		$isNull = is_null($subject);
	}

	return $isNull;
}

/**
 * 根据小括号获取内容
 */
function stack($subject, $debug=false) {
	$check_stack = array();

	$start_index = 0;
	$end_index = 0;

	$subject_length = strlen($subject);

	for ($index = 0; $index < $subject_length; $index++) {
		$s = substr($subject, $index, 1);
		if ($s == '(') {
			if ($start_index == 0) {
				$start_index = $index;
			}

			array_push($check_stack, $s);
		}

		if ($s == ')') {
			array_pop($check_stack);
			if (count($check_stack) == 0) {
				$end_index = $index;
				break;
			}
		}
        if($debug){
        	echo 'check_stack:';
        	var_dump($check_stack);
		    echo '<br>';
        }
		
	}

	$original = $subject;
	$content = substr($subject, $start_index + 1, $end_index - $start_index - 1);

	return array('original' => $original, 'content' => $content, 'start_index' => $start_index, 'end_index' => $end_index);
}

/**
 * 反向入栈获取（）内的信息
 */
function reserve_stack($subject, $debug=false) {
	$check_stack = array();

	$subject_length = strlen($subject);
	if ($subject_length <= 1) {
		return array(
		  'has_error'=>true,
		  'message'=>'校验字符串为空'
		);
	}

	$start_index = $subject_length;
	$end_index = $subject_length - 1;

	for ($index = $subject_length - 1; $index > 0; $index--) {
		$s = substr($subject, $index, 1);
		if ($s == ')') {
			// 若包含2个）则不满足备注条件
			if (count($check_stack) > 0) {
				return array(
				  'has_error'=>true,
				  'message'=>'包含2组括号，无需校验'
				);
			}
			array_push($check_stack, $s);
		}

		if ($s == '(') {
			array_pop($check_stack);
			if (count($check_stack) == 0) {
				$start_index = $index;
				break;
			}
		}
        if($debug){
        	echo 'check stack:';
        	var_dump($check_stack);
		    echo '<br>';
        }
		
	}

	$original = $subject;
	$content = substr($subject, $start_index + 1, $end_index - $start_index - 1);

	return array('original' => $original, 'content' => $content, 'start_index' => $start_index, 'end_index' => $end_index);
}
/**
 * 在两头去除$default_value
 * @param $subject mixed  需要处理的字符串
 * @param $default_value string 需要去除的字符
 */
function remove_str($subject, $default_value='-'){
	$subject = trim($subject);
	$len = strlen($subject);
	if($len==0) return $subject;
	
	$default_value = trim($default_value);
	
	if(preg_match('/^'.$default_value.'/', $subject)>0){
		$subject = substr($subject, strlen($default_value));
	}
	
	if(preg_match("/$default_value$/", $subject)>0){
		$subject = substr($subject, 0, $len - strlen($default_value));
	}
	
	return $subject;
}
/**
 * 替换特殊字符
 */
function replace_special($subject){
	$subject = trim($subject);
	$subject = str_replace('－', '-', $subject);
	$subject = str_replace('（', '(', $subject);
	$subject = str_replace('）', ')', $subject);
	
	return $subject;
}

 /**
 * 数据库记录转为array，并以keyname为key
 */
function array2map($resultDatas, $keyName, $keyName2=''){
	$array_data = array();
	if(count($resultDatas)==0){
		return $array_data;
	}
    
	$key_length2 = strlen($keyName2);
	foreach($resultDatas as $resultData){
		$array_data[$resultData[$keyName]] = $resultData;
		if($key_length2>0){
			$array_data[$resultData[$keyName2]] = $resultData;
		}
	}
	
	return $array_data;
}

/**
 * 求给出一个正整数，求出它的阶乘
 * @param $num int 要求阶乘的正整数
 * @return mixed 阶乘结果
 */
function factorial($num){
    if($num==1){
        return $num;
    }
    return $num * factorial($num-1);
}

/**
 * 全排列
 * @param $result array 结果对象
 * @param $array array 需要排列的数组
 * @param int $max 获取最大的排列
 */
function permute(&$result, $array, $max=1000) {
    $length = count($array);
    permute_full_array($result, $array, 0, $length - 1, $max);
}

/**
 * 标记，当前的位置值是否需要调换位置
 * @param $array array 需要排列的数组
 * @param $start int 起始位置
 * @param $end int 结束位置
 * @return bool 标记是否需要调换位置
 */
function swap_accepted($array, $start, $end) {
    for ($index = $start; $index < $end; $index++) {
        if ($array[$index] == $array[$end]) {
            return false;
        }
    }
    return true;
}

/**
 * 获取全排列的数组结果
 * @param $result array 存放结果的数组
 * @param $array array 需要排列的数组
 * @param $cursor int 当前游标
 * @param $end int 结束位置
 * @param int $max 获取最大的排列数
 */
function permute_full_array(&$result, $array, $cursor, $end, $max=1000) {
    if(count($result)>=$max) return;
    if ($cursor == $end) {
        array_push($result, $array);
    } else {
        for ($index = $cursor; $index <= $end; $index++) {
            if (!swap_accepted($array, $cursor, $index)) {
                continue;
            }
            list($array[$cursor], $array[$index]) = [$array[$index], $array[$cursor]];
            permute_full_array($result, $array, $cursor + 1, $end, $max);
            list($array[$cursor], $array[$index]) = [$array[$index], $array[$cursor]]; // 用于对之前交换过的数据进行还原
        }
    }
}

/**
 * 计算组合数（n>=m）
 * @param $n int 总的数目
 * @param $m int 需要的数目
 * @return int 结果数
 */
function combine_number($n, $m){
    $result = 1;
    $tmp = $n-$m+1;
    for($index=$n; $index>=$tmp; $index--){
        $result *= $index;
    }
    for($index=1; $index<=$m; $index++){
        $result /= $index;
    }
    return $result;
}

/**
 * 获取数组的组合信息
 * @param $originalArray array 需要组合的数组
 * @param $goalLength int 组合的长度
 * @return array 组合的结果数组
 */
function combine($originalArray, $goalLength, $max=0){
    $result = [];
    $original_array_count = count($originalArray);
    $flags = [];
    for($index=0; $index<$original_array_count; $index++){
        $flags[$index] = ($index<$goalLength) ? 1 : 0;
    }
    $compile_number = combine_number($original_array_count, $goalLength);
    $flag_count = count($flags)-1;
    array_push($result, get_combine_result($originalArray, $flags));
    if ($max>0){
        $compile_number = $max;
    }
    for($index=1; $index<$compile_number; $index++){
        $pos = 0;
        for($i=0; $i<$flag_count; $i++){
            $flag1 = $flags[$i];
            $flag2 = $flags[$i+1];
            if ($flag1==1 && $flag2==0){
                $flags[$i] = 0;
                $flags[$i+1]=1;
                $pos = $i;
                break;
            }
        }
        $sum = 0;
        for($i=0; $i<$pos; $i++){
            if($flags[$i]==1){
                $sum ++;
            }

        }
        for($i=0; $i<$pos; $i++){
            if($i<$sum){
                $flags[$i]=1;
            }else{
                $flags[$i]=0;
            }
        }
        array_push($result, get_combine_result($originalArray, $flags));
    }

    return $result;
}

function get_combine_result($originalArray, $flags){
    $result = [];
    foreach ($flags as $index=>$flag){
        if ($flag==1){
            array_push($result, $originalArray[$index]);
        }
    }
    return $result;
}
